package com.train.base.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.train.base.domain.ExamPlan;
import com.train.base.domain.ExamTestPaper;
import com.train.base.entity.bo.PaperAnswer;
import com.train.base.entity.bo.PaperGradingRecord;
import com.train.base.enums.PlanStatusEnums;
import com.train.base.service.IExamPlanService;
import com.train.base.service.IExamTestPaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 试卷管理Controller
 *
 * @author keke
 * @date 2024-04-01
 */
@RestController
@RequestMapping("/train/ExamTestPaper")
public class ExamTestPaperController extends BaseController {
    @Autowired
    private IExamTestPaperService examTestPaperService;
    @Autowired
    private IExamPlanService examPlanService;

    /**
     * 查询试卷管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ExamTestPaper examTestPaper) {
        startPage();
        List<ExamTestPaper> list = examTestPaperService.selectExamTestPaperList(examTestPaper);
        return getDataTable(list);
    }

    @GetMapping("/listCurrentUser")
    public TableDataInfo listCurrentUser() {
        startPage();
        ExamTestPaper examTestPaper = new ExamTestPaper();
        examTestPaper.setUserId(SecurityUtils.getUserId());
        List<ExamTestPaper> list = examTestPaperService.selectExamTestPaperList(examTestPaper);
        if (list.isEmpty()) {
            return getDataTable(list);
        }
        // 进行排名
        List<ExamPlan> plans = examPlanService.selectExamPlanByIds(list.stream().map(ExamTestPaper::getExemPlanId).toList());
        Map<Long, ExamPlan> planMap = plans.stream().filter(e -> e.getStatu().equals(PlanStatusEnums.FINISH.getCode())).collect(Collectors.toMap(ExamPlan::getId, Function.identity()));
        if (planMap.isEmpty()) {
            return getDataTable(list);
        }
        List<ExamTestPaper> examTestPapers = examTestPaperService.selectExamTestPaperByPlanIds(planMap.keySet().stream().toList());
        Map<Long, List<ExamTestPaper>> papeMap = examTestPapers.stream().collect(Collectors.groupingBy(ExamTestPaper::getExemPlanId));
        list.forEach(e -> {
            ExamPlan examPlan = planMap.get(e.getExemPlanId());
            if (Objects.isNull(examPlan)) {
                return;
            }
            long count = papeMap.get(e.getExemPlanId()).stream().filter(p -> p.getGainGrade() > e.getGainGrade()).count() + 1;
            e.setRanking((int) count);
        });
        return getDataTable(list);
    }

    /**
     * 导出试卷管理列表
     */
    @Log(title = "试卷管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExamTestPaper examTestPaper) {
        List<ExamTestPaper> list = examTestPaperService.selectExamTestPaperList(examTestPaper);
        ExcelUtil<ExamTestPaper> util = new ExcelUtil<ExamTestPaper>(ExamTestPaper.class);
        util.exportExcel(response, list, "试卷管理数据");
    }

    /**
     * 获取试卷管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(examTestPaperService.selectExamTestPaperById(id));
    }

    /**
     * 新增试卷管理
     */
    @Log(title = "试卷管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExamTestPaper examTestPaper) {
        return toAjax(examTestPaperService.insertExamTestPaper(examTestPaper));
    }

    /**
     * 修改试卷管理
     */
    @Log(title = "试卷管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExamTestPaper examTestPaper) {
        return toAjax(examTestPaperService.updateExamTestPaper(examTestPaper));
    }

    /**
     * 删除试卷管理
     */
    @Log(title = "试卷管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(examTestPaperService.deleteExamTestPaperByIds(ids));
    }

    /**
     * 领取试卷
     *
     * @param id
     * @return
     */
    @PutMapping(value = "receive")
    public AjaxResult receive(@RequestBody JSONObject object) {
        return AjaxResult.success(examTestPaperService.receive(object.getLong("id")));
    }

    /**
     * 获取某个试卷详情
     *
     * @param id
     * @return
     */
    @GetMapping(value = "getDetail")
    public AjaxResult getDetail(@RequestParam Long id) {
        return AjaxResult.success(examTestPaperService.getDetail(id));
    }

    /**
     * 提交试卷
     *
     * @param answer
     * @return
     */
    @PostMapping(value = "submitPaper")
    public AjaxResult submitPaper(@RequestBody PaperAnswer answer) {
        return toAjax(examTestPaperService.submitPaper(answer));
    }

    @PostMapping(value = "gradingPaper")
    public AjaxResult gradingPaper(@RequestBody PaperGradingRecord paperGradingRecord) {
        return toAjax(examTestPaperService.gradingPaper(paperGradingRecord));
    }


    /**
     * 前三次考试排名
     */
    @GetMapping("examRanking")
    public AjaxResult examRanking() {
        Map<Integer, List<ExamTestPaper>> testPapers = examTestPaperService.examRanking();
        return AjaxResult.success(testPapers);
    }

    /**
     * 近十次考试通过率
     */
    @GetMapping("passingRate")
    public AjaxResult passingRate() {
        return AjaxResult.success(examTestPaperService.passRate());
    }

    /**
     * 历史考试分数第一名
     */
    @GetMapping("historyExamFirst")
    public AjaxResult historyExamFirst() {
        return AjaxResult.success(examTestPaperService.historyExamFirst());
    }

    /**
     * 获取 错题饼状图占比
     */
    @GetMapping("errorProportion")
    public AjaxResult errorProportion() {
        return AjaxResult.success(examTestPaperService.errorProportion());
    }
}
